package net.cardgame.orcalecard;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import jp.jma.oraclecard.MyApplication;
import jp.jma.oraclecard.R;
import net.cardgame.oraclecard.common.Helper;
import net.cardgame.oraclecard.common.ImageClickable;
import net.cardgame.oraclecard.common.ThreadLoadImage;
import net.cardgame.oraclecard.common.onDeleteNewsBeanListener;
import net.cardgame.orcalecard.bean.CardBean;
import net.cardgame.orcalecard.bean.HistoryBean;
import net.cardgame.orcalecard.bean.NewsBean;
import net.cardgame.orcalecard.pref.SecurePreferences;
import net.cardgame.orcalecard.utils.ConstantValue;
import net.cardgame.orcalecard.utils.Utils;
import uk.co.senab.bitmapcache.BitmapLruCache;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.novoda.imageloader.core.ImageManager;
import com.novoda.imageloader.core.model.ImageTagFactory;

public class EditHistoryActivity extends Activity implements OnClickListener,
		onDeleteNewsBeanListener {
	ArrayList<HistoryBean> listHistory = new ArrayList<HistoryBean>();
	HistoryBean history;
	ArrayList<NewsBean> listNews = new ArrayList<NewsBean>();
	ImageView btnSave, img_deck;
	NewsBeanAdapter adapter;
	TextView txtMemory;
	ListView listView;
	int index;
	private ImageManager imageManager;
	private ImageTagFactory imageTagFactory;
	ImageClickable card1, card2, card3, card4;
	final static String X1 = "";
	final static String X2 = "X2";
	final static String X3 = "X3";
	private BitmapLruCache cache;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		cache = MyApplication.getInstance().getBitmapCache();
		setContentView(R.layout.edit_history_activity);
		initView();
		getHistory();
		loadHistoryInfo();
	}

	void initView() {
		findViewById(R.id.btnhelp_edit_history).setOnClickListener(this);
		findViewById(R.id.btnBack_edit_history).setOnClickListener(this);
		findViewById(R.id.btnSave_comment).setOnClickListener(this);
		txtMemory = (TextView) findViewById(R.id.txtmemory_edit_history);
		card1 = (ImageClickable) findViewById(R.id.img_card1_save);
		card2 = (ImageClickable) findViewById(R.id.img_card2_save);
		card3 = (ImageClickable) findViewById(R.id.img_card3_save);
		card4 = (ImageClickable) findViewById(R.id.img_card4_save);
		img_deck = (ImageView) findViewById(R.id.img_deck_save);
	}

	void getHistory() {
		Gson gson = new Gson();
		Type listOfHistoryBean = new TypeToken<List<HistoryBean>>() {
		}.getType();
		SecurePreferences appPreferences = new SecurePreferences(this,
				ConstantValue.APP_PREFERENCES,
				ConstantValue.PREFERENCES_SECRET_KEY, true);
		if (appPreferences.containsKey(ConstantValue.HISTORY_KEY)) {
			String strHistory = appPreferences
					.getString(ConstantValue.HISTORY_KEY);
			listHistory = gson.fromJson(strHistory, listOfHistoryBean);
		}
		Bundle bundle = getIntent().getExtras();
		int historyId = bundle.getInt("historyId");
		int size = listHistory.size();
		for (int i = 0; i < size; i++) {
			if (listHistory.get(i).id == historyId) {
				index = i;
				history = listHistory.get(i);
				listNews = history.newsBeans;
				break;
			}
		}
	}

	void loadHistoryInfo() {
		ImageView img_number_card = (ImageView) findViewById(R.id.img_number_of_card_save);
		TextView txtQuestion = (TextView) findViewById(R.id.txtquestion_edithistory);
		if (history.question != null && history.question != "")
			txtQuestion.setText(history.question);
		TextView txtTitle = (TextView) findViewById(R.id.txttitle_edit_history);
		txtTitle.setText(history.strDateTime + " の結果");
		TextView txtDeckTitle = (TextView) findViewById(R.id.txttitle_deck_save);
		txtDeckTitle.setText(history.deckTitle);
		if (history.deckbeanId != 999) {
			String tt = convertIdToStringId(history.deckbeanId);
			String patch_img_deck = ConstantValue.BASE_URL + "Card_" + tt
					+ "/c" + tt + "i.png";
			initImageLoader();
			setImageTag(img_deck, patch_img_deck);
			loadImage(img_deck);
		} else {
			img_deck.setImageResource(R.drawable.c999i);
		}
		String path = getCardPatchByCardId(history.cardBeans.get(0));
		card1.setPath(path);
		new ThreadLoadImage(this, handlerLoadImage, path, card1, 1).start();
		if (history.cardBeans.get(0).isJump)
			findViewById(R.id.img_jump_card1_save).setVisibility(View.VISIBLE);
		switch (history.cardBeans.size()) {
		case 3:
			path = getCardPatchByCardId(history.cardBeans.get(1));
			card2.setPath(path);
			new ThreadLoadImage(this, handlerLoadImage, path, card2, 2).start();
			path = getCardPatchByCardId(history.cardBeans.get(2));
			card3.setPath(path);
			new ThreadLoadImage(this, handlerLoadImage, path, card3, 3).start();
			card2.setVisibility(View.VISIBLE);
			card3.setVisibility(View.VISIBLE);
			img_number_card.setImageResource(R.drawable.result_draw3);
			if (history.cardBeans.get(1).isJump)
				findViewById(R.id.img_jump_card2_save).setVisibility(
						View.VISIBLE);
			if (history.cardBeans.get(2).isJump)
				findViewById(R.id.img_jump_card3_save).setVisibility(
						View.VISIBLE);
			break;
		case 4:
			path = getCardPatchByCardId(history.cardBeans.get(1));
			card2.setPath(path);
			new ThreadLoadImage(this, handlerLoadImage, path, card2, 2).start();
			path = getCardPatchByCardId(history.cardBeans.get(2));
			card3.setPath(path);
			new ThreadLoadImage(this, handlerLoadImage, path, card3, 3).start();
			path = getCardPatchByCardId(history.cardBeans.get(3));
			card4.setPath(path);
			new ThreadLoadImage(this, handlerLoadImage, path, card4, 4).start();
			card2.setVisibility(View.VISIBLE);
			card3.setVisibility(View.VISIBLE);
			card4.setVisibility(View.VISIBLE);
			img_number_card.setImageResource(R.drawable.result_draw4);
			if (history.cardBeans.get(1).isJump)
				findViewById(R.id.img_jump_card2_save).setVisibility(
						View.VISIBLE);
			if (history.cardBeans.get(2).isJump)
				findViewById(R.id.img_jump_card3_save).setVisibility(
						View.VISIBLE);
			if (history.cardBeans.get(3).isJump)
				findViewById(R.id.img_jump_card4_save).setVisibility(
						View.VISIBLE);
			break;

		default:
			break;
		}
		listView = (ListView) findViewById(R.id.listView_edit_history);
		if (history.newsBeans != null) {
			adapter = new NewsBeanAdapter(this, history.newsBeans);
			listView.setAdapter(adapter);
			Helper.getListViewSize(listView);
		}
	}

	Handler handlerLoadImage = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				card1.setImageDrawable((Drawable) msg.obj);
				card1.setOnClickListener(EditHistoryActivity.this);
				break;
			case 2:
				card2.setImageDrawable((Drawable) msg.obj);
				card2.setOnClickListener(EditHistoryActivity.this);
				break;

			case 3:
				card3.setImageDrawable((Drawable) msg.obj);
				card3.setOnClickListener(EditHistoryActivity.this);
				break;

			case 4:
				card4.setImageDrawable((Drawable) msg.obj);
				card4.setOnClickListener(EditHistoryActivity.this);
				break;
			default:
				break;
			}

		};
	};

	String convertIdToStringId(int id) {
		return id < 10 ? "0" + id : "" + id;
	}

	/**
	 * Get patch image file
	 * 
	 * @param cardBean
	 * 
	 * @return patch to image
	 */

	String getCardPatchByCardId(CardBean cardBean) {
		return ConstantValue.getPatchCardData(this) + "Card_"
				+ convertIdToStringId(cardBean.deckId) + "/X3/en_c"
				+ convertIdToStringId(cardBean.deckId)
				+ convertIdToStringId(cardBean.cardId) + ".png";
	}

	void showDialog(String title) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// Creates textview for centre title
		TextView myMsg = new TextView(this);
		myMsg.setText(title);
		myMsg.setGravity(Gravity.CENTER_HORIZONTAL);
		myMsg.setTextSize(20);
		myMsg.setTextColor(Color.WHITE);
		// set custom title
		builder.setCustomTitle(myMsg);
		// builder.setMessage("Check your email and verify your username and password...");
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.dismiss();
			}
		});
		AlertDialog dialog = builder.show();
		// Create custom message
		// TextView messageText = (TextView) dialog
		// .findViewById(android.R.id.message);
		// messageText.setGravity(Gravity.CENTER);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btnhelp_edit_history:
			Intent intent = new Intent(this, HelpActivity.class);
			intent.putExtra(HelpActivity.KEY_HELP_INDEX, 1);
			startActivityForResult(intent, 0);
			overridePendingTransition(R.anim.slide_in_right,
					R.anim.slide_out_left);
			break;
		case R.id.btnBack_edit_history:
			saveHistory();
			this.finish();
			break;
		case R.id.btnSave_comment:
			if (!txtMemory.getText().toString().matches("")) {
				showDialog("本体に保存しました");
				NewsBean newsBean = getNewsBean();
				if (adapter == null) {
					listNews = new ArrayList<NewsBean>();
					newsBean.id = 1;
					listNews.add(newsBean);
					adapter = new NewsBeanAdapter(this, listNews);
					listView.setAdapter(adapter);
				} else {
					newsBean.id = listNews.size() + 1;
					adapter.addNewsBean(newsBean);
				}
				Helper.getListViewSize(listView);
				// for (NewsBean newss : listNews) {
				// Utils.DLog("list News bean", newss.toString());
				// }

			}
			break;
		case R.id.img_card1_save:
			gotoCardDetail(history.cardBeans.get(0));
			break;
		case R.id.img_card2_save:
			gotoCardDetail(history.cardBeans.get(1));
			break;
		case R.id.img_card3_save:
			gotoCardDetail(history.cardBeans.get(2));
			break;
		case R.id.img_card4_save:
			gotoCardDetail(history.cardBeans.get(3));
			break;
		default:
			break;
		}
	}

	NewsBean getNewsBean() {
		Calendar c = Calendar.getInstance();
		Date now = c.getTime();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int day = c.get(Calendar.DAY_OF_MONTH);
		int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
		int hh = c.get(Calendar.HOUR_OF_DAY);
		int mm = c.get(Calendar.MINUTE);
		String dayWeek = "";
		switch (dayOfWeek) {
		case 2:
			dayWeek = "Mon";
			break;
		case 3:
			dayWeek = "Tue";
			break;
		case 4:
			dayWeek = "Wed";
			break;
		case 5:
			dayWeek = "Thu";
			break;
		case 6:
			dayWeek = "Fri";
			break;
		case 7:
			dayWeek = "Sat";
			break;
		case 8:
			dayWeek = "Sun";
			break;
		default:
			break;
		}
		String strDatetime = year + "年" + convertIdToStringId(month) + "月"
				+ convertIdToStringId(day) + "日(" + dayWeek + ") "
				+ convertIdToStringId(hh) + ":" + convertIdToStringId(mm);
		NewsBean newsBean = new NewsBean();
		newsBean.sumary = txtMemory.getText().toString();
		newsBean.datetime = strDatetime;
		newsBean.time = now;
		return newsBean;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
	}

	void saveHistory() {
		history.newsBeans = listNews;
		listHistory.set(index, history);
		Gson gson = new Gson();
		Type listOfHistoryBean = new TypeToken<List<HistoryBean>>() {
		}.getType();
		SecurePreferences appPreferences = new SecurePreferences(this,
				ConstantValue.APP_PREFERENCES,
				ConstantValue.PREFERENCES_SECRET_KEY, true);
		String save = gson.toJson(listHistory, listOfHistoryBean);
		appPreferences.put(ConstantValue.HISTORY_KEY, save);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			saveHistory();
			this.finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onDeleted(NewsBean newsBean) {
		// TODO Auto-generated method stub
		listNews.remove(newsBean);
		Helper.getListViewSize(listView);
	}

	void gotoCardDetail(CardBean cardBean) {
		Intent intent = new Intent(this, CardDetailActivity.class);
		intent.putExtra("deckId", cardBean.deckId);
		intent.putExtra("cardId", cardBean.cardId);
		startActivityForResult(intent, 0);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
	}

	String getCardPatchByCardId(CardBean cardBean, String typeImage) {
		if (typeImage == X1)
			typeImage = "";
		else
			typeImage = "/" + typeImage + "/";
		String result = ConstantValue.getPatchCardData(this) + "Card_"
				+ convertIdToStringId(cardBean.deckId) + typeImage + "en_c"
				+ convertIdToStringId(cardBean.deckId)
				+ convertIdToStringId(cardBean.cardId) + ".png";
		return result;
	}

	private void ClearCache() {
		List<CardBean> list = history.cardBeans;
		for (CardBean card : list) {
			cache.removeFromMemory(getCardPatchByCardId(card, X1));
			cache.removeFromMemory(getCardPatchByCardId(card, X3));
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		ClearCache();
		super.onDestroy();
	}

	private void initImageLoader() {
		imageManager = MyApplication.getInstance().getImageLoader();
		imageTagFactory = createImageTagFactory();
	}

	private ImageTagFactory createImageTagFactory() {
		ImageTagFactory imageTagFactory = ImageTagFactory.newInstance();
		imageTagFactory.setHeight(248);
		imageTagFactory.setWidth(188);
		imageTagFactory.setDefaultImageResId(R.drawable.cardi_tranparent);
		imageTagFactory.setErrorImageId(R.drawable.cardi_tranparent);
		imageTagFactory.setSaveThumbnail(true);
		return imageTagFactory;
	}

	private void setImageTag(ImageView view, String url) {
		view.setTag(imageTagFactory.build(url, this));
	}

	private void loadImage(ImageView view) {
		imageManager.getLoader().load(view);
	}

}
